package com.xlw.authenticator;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tandong.sa.vl.Request;
import com.xlw.application.AppConfig;
import com.xlw.onroad.R;
import com.xlw.utils.IVolleyCallback;
import com.xlw.utils.VolleyUtil;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by xinliwei on 2015/7/7.
 *
 * 用于显示登录表单
 */
public class AuthenticatorActivity extends AccountAuthenticatorActivity{

    private static final String TAG = AuthenticatorActivity.class.getCanonicalName();

    public static final String PARAM_ACCOUNT_TYPE = "com.xlw.onroad";
    public static final String PARAM_AUTHTOKEN_TYPE = "authtokenType";
    public static final String PARAM_USER = "user";
    public static final String PARAM_CONFIRMCREDENTIALS = "confirmCredentials";

    private AccountManager mAccountManager;
    private String mAuthToken;
    private String mAuthTokenType;
    private Boolean mConfirmCredentials = false;

    private String mUsername;
    private String mPassword;

    EditText mUsernameEdit;
    EditText mPasswordEdit;
    TextView mMessage;
    Button mSignInButton;

    /** Was the original caller asking for an entirely new account? */
    protected boolean mRequestNewAccount = false;
    private String mUser;

    VolleyUtil volleyUtil;
    Request volleyRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAccountManager = AccountManager.get(this);
        checkMaximumNumberOfAccounts();

        final Intent intent = getIntent();

        mUser = intent.getStringExtra(PARAM_USER);
        mAuthTokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
        mRequestNewAccount = mUsername == null;
        mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS, false);

        Log.i(TAG, "    request new: " + mRequestNewAccount);
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.activity_authenticator_login);

        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);

        findViews();
        initFields();
    }

    private void findViews() {
        mUsernameEdit = (EditText)findViewById(R.id.mUsernameEdit);
        mPasswordEdit = (EditText)findViewById(R.id.mPasswordEdit);
        mMessage = (TextView)findViewById(R.id.mMessage);
        mSignInButton = (Button)findViewById(R.id.btn_submit);
    }

    private void initFields() {
        mUsernameEdit.setText(mUser);
        mMessage.setText(getMessage());

        mSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleLogin(v);
            }
        });
    }

    // 当用户输入登录信息并点击"OK"按钮后,handleLogin()就会被调用
    private void handleLogin(View view){
        if(mRequestNewAccount){
            mUsername = mUsernameEdit.getText().toString();
        }
        mPassword = mPasswordEdit.getText().toString();

        // 用户输入项非空检测
        if(TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)){
            mMessage.setText(getMessage());
        }

        showProgress();

        volleyUtil = new VolleyUtil(new IVolleyCallback() {
            @Override
            public void responseString(String responseText) {
            }

            @Override
            public void responseJSONObject(JSONObject jsonObject) {
                Boolean result = "{\"result\": \"ok\"}".equals(jsonObject.toString());
                onAuthenticationResult(result);
            }

            @Override
            public void responseJsonArray(JSONArray jsonArray) {
            }
        });

        String login_params = "?username=" + mUsername + "&password=" + mPassword;
        String login_url = AppConfig.URL_BASE + AppConfig.LOGIN + login_params;
        volleyRequest = volleyUtil.requestJSONObject(login_url);
    }

    // 向AuthenticatorActivity返回结果
    public void onAuthenticationResult(Boolean result){
        hideProgress();     // 隐藏进度对话框

        if(result){
            // 如果服务验证成功
            if(!mConfirmCredentials){
                finishLogin();
            }
        }else{
            // 否则就向用户显示一条错误信息提醒用户重新登录
            mMessage.setText("账户和/或密码不正确.");
        }
    }

    private void finishLogin(){
        final Account account = new Account(mUsername,PARAM_ACCOUNT_TYPE);

        // 设置新密码
        if(mRequestNewAccount){
            // 如果设置了请求创建新账户的标记,就通过AccountManager创建一个账户
            mAccountManager.addAccountExplicitly(account,mPassword,null);

//            Bundle bundle = new Bundle();
//            ContentResolver.addPeriodicSync(account, OnRoadContentProvider.AUTHORITY, bundle, 300);
        }else {
            // 如果账户已经存在,就设置一个新密码
            mAccountManager.setPassword(account,mPassword);
        }

        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,mUsername);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

        if(mAuthTokenType != null && mAuthTokenType.equals(PARAM_AUTHTOKEN_TYPE)){
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        }

        // 设置结果
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("登录");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                if (volleyUtil != null) {
                    volleyUtil.cancelRequest(volleyRequest);
                    finish();
                }
            }
        });
        return dialog;
    }

    private void showProgress() {
        showDialog(0);
    }

    private void hideProgress() {
        dismissDialog(0);
    }

    private CharSequence getMessage() {

        if (TextUtils.isEmpty(mUsername)) {
            return "新账户";
        }

        if (TextUtils.isEmpty(mPassword)) {
            return "密码不能为空";
        }

        return null;
    }

    private void checkMaximumNumberOfAccounts() {
        Account[] accounts = mAccountManager.getAccountsByType(PARAM_ACCOUNT_TYPE);

        if (accounts.length != 0) {
            Toast.makeText(this, "超过一个账户", Toast.LENGTH_SHORT).show();
            finish();
        }

    }

}
